package com.qf.controller;

import com.qf.enums.InterfaceExceptionEnums;
import com.qf.feign.CacheFeign;
import com.qf.pojo.SmsInterfaceForm;
import com.qf.service.SmsInterfaceService;
import com.qf.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 接收某京及icbc这些客户的请求
 *
 * @author lixu
 */
@RestController
@RequestMapping("/sms")
public class SmsInterfaceController {

    @Value("${sms.content.length}")
    private Integer smsContentLength;

    @Value("${ip-header}")
    private String[] ipHeader;

    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private SmsInterfaceService smsInterfaceService;

    /**
     * 请求
     */
    @PostMapping("/smsInterface")
    public Result smsInterface(SmsInterfaceForm form, HttpServletRequest request) {
        //1：客户的ID必须存在  否则不是我们公司的消费者 我们不处理
        String cacheKey = "CLIENT:" + form.getClientID();
        Map map = cacheFeign.hMGet(cacheKey);
        if(null == map || map.size() == 0){
            return Result.error(101,"认证错:....");
        }
        //2:- 手机号合法性
        String mobile = form.getMobile();
        if(StringUtils.isEmpty(mobile)){
            return Result.error(105,"手机号错误");
        }
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        String[] ms = mobile.split(",");
        if(null != ms && ms.length > 0){
            Set<String> errors = new HashSet<>();
            for (String m : ms) {
          /*      if(!m.matches(regex)){
                    return Result.error(105,"手机号格式不正确");
                }*/
                if(!m.matches(regex)){
                    errors.add(m);
                }
            }
            //统一处理
            if(errors.size() > 0){//[13456677777,1234324432,546564634563543,42341243]
                return Result.error(105,"手机号"+ Arrays.asList(errors)+"错误");
            }
        }

        //3:     - 客户IP的合法性
        String ip = getIp(request);
        //0:0:0:0:0:1   webFlux IPV6  Tomcat IPV4
        form.setIp(ip);
        String ipaddress = (String) map.get("ipaddress");
        if(StringUtils.isEmpty(ipaddress)){
            return Result.error(103,"IP校验错误");
        }
        System.out.println("ip:" + ip);
        if(!ipaddress.equalsIgnoreCase(ip)){
            return Result.error(103,"IP不合法");
        }
        //4:   - 客户密码的合法性
        String pwd = form.getPwd();
        if(StringUtils.isEmpty(pwd)){
            return Result.error(InterfaceExceptionEnums.INTERFACE_PWD_ERROR);
        }
        String pwd1 = (String) map.get("pwd");
        if(!pwd.equals(pwd1)){
            return Result.error(InterfaceExceptionEnums.INTERFACE_PWD_ERROR);
        }
        //5  - 用户发送信息的长度
        String content = form.getContent();
        if(StringUtils.isEmpty(content)){
            return Result.error(104,"消息为空");
        }
        if(content.length() > smsContentLength){
            return Result.error(104,"消息超长（不能超过500个字)");
        }
        //发送消息到RabbitMQ中
        smsInterfaceService.sendMQ(form);
        return Result.ok("成功");

    }

    /**
     * 获取真实IP地址
     * @param request
     * @return
     */
    public String getIp(HttpServletRequest request){
        String ip = null;
        if(null != ipHeader && ipHeader.length >0){
            for (String ipH : ipHeader) {
                ip = request.getHeader(ipH);
                if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
                    continue;
                }else{
                    return ip;
                }
            }

        }
        if(StringUtils.isEmpty(ip)){
            //没有使用Nginx这样代理
            return request.getRemoteAddr();
        }
        return null;
    }
}
